//
//  UIView+WMAlert.m
//  LvXi_newVersion
//
//  Created by 王敏 on 16/8/20.
//  Copyright © 2016年 SJT. All rights reserved.
//

#import "UIView+WMAlert.h"

#import "CircleGradientColorView.h"
typedef void(^alertHandleWithTextFiled)(NSInteger buttonIndex,UITextField*textField);
@implementation UIView (WMAlert)

static const char kContainerView='\0';
static const char kWindow='\0';
static const char kMaskLayer='\0';
static const char kCoverView='\0';
static const char kHandleBlock='\0';
static const char kTextField='\0';
static const char kContainerViewBotton='\0';

-(void)alertWithTitle:(NSString *)title mesege:(NSString *)messege buttons:(NSArray *)buttons handle:(alertHandle)handle{
    CGFloat ratio = 0.6;
    UIWindow * window = [[UIApplication sharedApplication].delegate window];
    UIView * containerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, window.width * ratio, window.height * 0.5)];
    containerView.layer.borderWidth = 0.5;
    containerView.layer.borderColor = RGBAColor(0, 0, 0, 0.7).CGColor;
    
    containerView.backgroundColor = RGBAColor(255,255,255,0.9);
    [containerView addRadius:10];

    
    UIView * coverView = [[UIView alloc] initWithFrame:window.bounds];
    coverView.backgroundColor = RGBAColor(0, 0, 0, 0.7);
    [window addSubview:coverView];
    [window addSubview:containerView];
    UILabel * titleLabel=nil;
    if(title&&title.length!=0){
       titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, containerView.width, 50)];
        titleLabel.text = title;
        titleLabel.font = [UIFont systemFontOfSize:12];
        titleLabel.layer.borderWidth = 0.5;
        titleLabel.layer.borderColor = RGBAColor(0, 0, 0, 0.7).CGColor;
        titleLabel.textColor = [UIColor blackColor];
        titleLabel.textAlignment = NSTextAlignmentCenter;
        [containerView addSubview:titleLabel];
    }
    UILabel * messegeLabel=nil;
    if(messege&&messege.length!=0){
        messegeLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, containerView.width, 50)];
        messegeLabel.text = messege;
        messegeLabel.font = [UIFont systemFontOfSize:12];
        messegeLabel.layer.borderWidth = 0;
        messegeLabel.layer.borderColor = RGBAColor(0, 0, 0, 0.7).CGColor;
        messegeLabel.textColor = [UIColor blackColor];
        messegeLabel.textAlignment = NSTextAlignmentCenter;
        messegeLabel.numberOfLines = 0;
        messegeLabel.y = (titleLabel!=nil?(titleLabel.botton-0.5):0);
        messegeLabel.x = 10;
        messegeLabel.size = [messege sizeInAre:CGSizeMake(containerView.width-20, MAXFLOAT) font:messegeLabel.font];
        messegeLabel.height+=10;
        messegeLabel.width =containerView.width-20;
        [containerView addSubview:messegeLabel];
    }
     if(buttons.count == 2){
        CGFloat width = (containerView.width) * 0.5;
        CGFloat height = 35;
        [buttons enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            UIButton * button = [UIButton buttonWithType:UIButtonTypeSystem];
            [button setTitle:obj forState:UIControlStateNormal];
            [button setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
            button.titleLabel.font = [UIFont systemFontOfSize:12];
            button.layer.borderWidth = 0.5;
            button.layer.borderColor = RGBAColor(0, 0, 0, 0.7).CGColor;
            button.x = idx*(width)-(idx==0?0:0.25);
            button.y = (messegeLabel!=nil?(messegeLabel.botton-0.5):(titleLabel!=nil?(titleLabel.botton-0.5):0));
            button.size = CGSizeMake(width+0.25, height);
            button.tag = idx;
            [button addTarget:self action:@selector(alertViewButtonClick:) forControlEvents:UIControlEventTouchUpInside];
            [containerView addSubview:button];
        }];
    }else{
        CGFloat width = (containerView.width);
        CGFloat height = 35;
        [buttons enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            UIButton * button = [UIButton buttonWithType:UIButtonTypeSystem];
            [button setTitle:obj forState:UIControlStateNormal];
            [button setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
            button.titleLabel.font = [UIFont systemFontOfSize:12];
            button.layer.borderWidth = 0.5;
            button.layer.borderColor = RGBAColor(0, 0, 0, 0.7).CGColor;
            button.x = 0;
            button.y = ((messegeLabel!=nil?(messegeLabel.botton-0.5):(titleLabel!=nil?(titleLabel.botton-0.5):0)))+idx*(height-0.5)-(idx==0?0:0);
            button.size = CGSizeMake(width+0.25, height);
            button.tag = idx;
            [button addTarget:self action:@selector(alertViewButtonClick:) forControlEvents:UIControlEventTouchUpInside];
            [containerView addSubview:button];
        }];
    }
    CGFloat containerViewHeight = ((messegeLabel!=nil?(messegeLabel.botton-0.5):(titleLabel!=nil?(titleLabel.botton-0.5):0))) + (buttons.count==2?(35):(buttons.count*35))-(buttons.count==2?0.5:(buttons.count*0.5));

    containerView.width = window.width * ratio;
    containerView.height = containerViewHeight;

    
    containerView.centerY = window.centerY;
    containerView.centerX = window.centerX;
    objc_setAssociatedObject(self, &kContainerView, containerView, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    objc_setAssociatedObject(self, &kWindow, window, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    objc_setAssociatedObject(self, &kCoverView, coverView, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    objc_setAssociatedObject(self, &kHandleBlock, handle, OBJC_ASSOCIATION_COPY);
    
    
    containerView.layer.transform = CATransform3DScale(containerView.layer.transform, 0.01, 0.01, 1);
    CABasicAnimation * scale1 = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    scale1.toValue = @(1.3);
    scale1.duration = 0.1;
    scale1.fillMode = kCAFillModeForwards;
    scale1.removedOnCompletion = NO;
    
    CABasicAnimation * scale2 = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    scale2.toValue = @(1);
    scale2.duration = 0.1;
    scale2.fillMode = kCAFillModeForwards;
    scale2.beginTime = 0.1;
    scale2.removedOnCompletion = NO;
    
    CABasicAnimation * scale3 = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    scale3.toValue = @(1.3);
    scale3.duration = 0.1;
    scale3.beginTime = 0.2;
    scale3.fillMode = kCAFillModeForwards;
    scale3.removedOnCompletion = NO;
    
    CABasicAnimation * scale4 = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    scale4.toValue = @(1);
    scale4.duration = 0.1;
    scale4.fillMode = kCAFillModeForwards;
    scale4.beginTime = 0.3;
    scale4.removedOnCompletion = NO;
    
    CAAnimationGroup * group = [CAAnimationGroup animation];
    group.animations = @[scale1,scale2,scale3,scale4];
    group.fillMode = kCAFillModeForwards;
    group.removedOnCompletion = NO;
    group.delegate = self;
    [containerView.layer addAnimation:group forKey:nil];
    
}

-(void)alertWithTitle:(NSString *)title mesege:(NSString *)messege buttons:(NSArray *)buttons handle:(alertHandle)handle hiddenAfter:(NSTimeInterval)time complete:(void (^)())complete{
    [self alertWithTitle:title mesege:messege buttons:buttons handle:handle];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(time * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self dismissAlert];
        if(complete)complete();
    });
}

-(void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag{
    UIView * containerView = objc_getAssociatedObject(self, &kContainerView);
    containerView.layer.transform = CATransform3DIdentity;
}

-(void)alertViewButtonClick:(UIButton*)button{
    alertHandle handle = objc_getAssociatedObject(self,&kHandleBlock);
    [self dismissAlert];
    if(handle){
        handle(button.tag);
    }
}

-(void)alertViewWithTextFieldButtonClick:(UIButton*)button{
    [self dismissAlert];
    alertHandleWithTextFiled handle = objc_getAssociatedObject(self, &kHandleBlock);
    if(handle){
        handle(button.tag,(UITextField*)(objc_getAssociatedObject(self, &kTextField)));
    }
}


-(void)dismissAlert{
    UIView * containerView = objc_getAssociatedObject(self, &kContainerView);
    UIView * coverView = objc_getAssociatedObject(self, &kCoverView);
    for (UIView * v in containerView.subviews) {
        [v removeFromSuperview];
    }
    [coverView removeFromSuperview];
    CAShapeLayer * layer = objc_getAssociatedObject(self, &kMaskLayer);
    [layer removeFromSuperlayer];
    [containerView removeFromSuperview];
}


-(void)alertWithMessege:(NSString *)messege{
    UIWindow * window = [[UIApplication sharedApplication].delegate window];
    UIFont * labelFont = [UIFont systemFontOfSize:17];
    
    
    UILabel * messegeLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth*0.6,0)];
    messegeLabel.font = labelFont;
    messegeLabel.text = messege;
    messegeLabel.numberOfLines = 0;
    messegeLabel.textAlignment = NSTextAlignmentCenter;
    messegeLabel.size = [messegeLabel.text sizeInAre:CGSizeMake(messegeLabel.width, MAXFLOAT) font:labelFont];
    messegeLabel.width = window.width * 0.6;
    messegeLabel.height +=10;
    [window addSubview:messegeLabel];
    
    messegeLabel.y = window.height;
    messegeLabel.centerX = window.width*0.5;
    messegeLabel.backgroundColor = [UIColor colorWithWhite:0.5 alpha:1];
    [messegeLabel addRadius:5];
    messegeLabel.alpha = 0;
    [UIView animateWithDuration:0.3 animations:^{
        messegeLabel.y = window.height - messegeLabel.height - 100;
        messegeLabel.alpha = 1;
    }];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [UIView animateWithDuration:0.3 animations:^{
            messegeLabel.alpha = 0;
            messegeLabel.y = window.height;
            
        }completion:^(BOOL finished) {
            [messegeLabel removeFromSuperview];
        }];
    });
}


-(void)showLoading{
    UIWindow * window = [[UIApplication sharedApplication].delegate window];
    CGFloat ratio = 0.6;
    
    CircleGradientColorView * containerView = [[CircleGradientColorView alloc] initWithFrame:CGRectMake(0, 0, window.width * ratio,window.width * ratio)];
    
    containerView.backgroundColor = RGBAColor(0, 0, 0, 0.7);
    containerView.center = window.center;
    [containerView addRadius:10];
    
    
    UIView * coverView = [[UIView alloc] initWithFrame:window.bounds];
    coverView.backgroundColor = [UIColor clearColor];
    [window addSubview:coverView];
    [coverView addSubview:containerView];
    [coverView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hidden:)]];
    

    
}

-(void)hidden:(UITapGestureRecognizer*)gesture{
    UIView * v = gesture.view;
    for (UIView * v1 in v.subviews) {
        [v1 removeFromSuperview];
    }
    [v removeFromSuperview];
    [v.superview removeFromSuperview];
}

-(void)alertWithTitle:(NSString *)title placeHolder:(NSString *)placeHolder buttons:(NSArray *)buttons handle:(void (^)(NSInteger, UITextField *))handle{
    CGFloat ratio = 0.7;
    UIWindow * window = [[UIApplication sharedApplication].delegate window];
    UIView * containerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, window.width * ratio, window.height * 0.5)];
    containerView.layer.borderWidth = 0.5;
    containerView.layer.borderColor = RGBAColor(0, 0, 0, 0.7).CGColor;
    
    containerView.backgroundColor = RGBAColor(255,255,255,0.9);
    [containerView addRadius:10];
    
    UIView * coverView = [[UIView alloc] initWithFrame:window.bounds];
    coverView.backgroundColor = RGBAColor(0, 0, 0, 0.7);
    [window addSubview:coverView];
    
    [window addSubview:containerView];
    UILabel * titleLabel=nil;
    if(title&&title.length!=0){
        titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, containerView.width, 50)];
        titleLabel.text = title;
        titleLabel.font = [UIFont systemFontOfSize:12];
        titleLabel.layer.borderWidth = 0.5;
        titleLabel.layer.borderColor = RGBAColor(0, 0, 0, 0.7).CGColor;
        titleLabel.textColor = [UIColor blackColor];
        titleLabel.textAlignment = NSTextAlignmentCenter;
        [containerView addSubview:titleLabel];
    }
    UITextField * textField =[[UITextField alloc] initWithFrame:CGRectMake(2, 2, containerView.width-4, 40)];
    textField.placeholder = placeHolder;
    textField.font = [UIFont systemFontOfSize:12];
    textField.borderStyle = UITextBorderStyleRoundedRect;
    textField.y = (titleLabel!=nil?(titleLabel.botton-0.5):0)+2;
    [containerView addSubview:textField];
    textField.returnKeyType = UIReturnKeyDone;
    
    textField.delegate = self;
    if(buttons.count == 2){
        CGFloat width = (containerView.width) * 0.5;
        CGFloat height = 35;
        [buttons enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            UIButton * button = [UIButton buttonWithType:UIButtonTypeSystem];
            [button setTitle:obj forState:UIControlStateNormal];
            [button setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
            button.titleLabel.font = [UIFont systemFontOfSize:12];
            button.layer.borderWidth = 0.5;
            button.layer.borderColor = RGBAColor(0, 0, 0, 0.7).CGColor;
            button.x = idx*(width)-(idx==0?0:0.25);
            button.y = (textField!=nil?(textField.botton-0.5):(titleLabel!=nil?(titleLabel.botton-0.5):0))+2;
            button.size = CGSizeMake(width+0.25, height);
            button.tag = idx;
            [button addTarget:self action:@selector(alertViewWithTextFieldButtonClick:) forControlEvents:UIControlEventTouchUpInside];
            [containerView addSubview:button];
        }];
    }else{
        CGFloat width = (containerView.width);
        CGFloat height = 35;
        [buttons enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            UIButton * button = [UIButton buttonWithType:UIButtonTypeSystem];
            [button setTitle:obj forState:UIControlStateNormal];
            [button setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
            button.titleLabel.font = [UIFont systemFontOfSize:12];
            button.layer.borderWidth = 0.5;
            button.layer.borderColor = RGBAColor(0, 0, 0, 0.7).CGColor;
            button.x = 0;
            button.y = ((textField!=nil?(textField.botton-0.5):(titleLabel!=nil?(titleLabel.botton-0.5):0)))+idx*(height-0.5)-(idx==0?0:0);
            button.size = CGSizeMake(width+0.25, height);
            button.tag = idx;
            [button addTarget:self action:@selector(alertViewWithTextFieldButtonClick:) forControlEvents:UIControlEventTouchUpInside];
            [containerView addSubview:button];
        }];
    }
    CGFloat containerViewHeight = ((textField!=nil?(textField.botton-0.5):(titleLabel!=nil?(titleLabel.botton-0.5):0))) + (buttons.count==2?(35):(buttons.count*35))-(buttons.count==2?0.5:(buttons.count*0.5));
    
    containerView.width = window.width * ratio;
    containerView.height = containerViewHeight;
    
    containerView.centerY = window.centerY;
    containerView.centerX = window.centerX;
    
    objc_setAssociatedObject(self, &kContainerView, containerView, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    objc_setAssociatedObject(self, &kWindow, window, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    objc_setAssociatedObject(self, &kCoverView, coverView, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    objc_setAssociatedObject(self, &kHandleBlock, handle, OBJC_ASSOCIATION_COPY);
    objc_setAssociatedObject(self, &kTextField, textField, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    CGFloat contentViewBotton = containerView.y + containerView.height;
    objc_setAssociatedObject(self, &kContainerViewBotton, @(contentViewBotton), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    //增加监听，当键盘出现或改变时收出消息
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    
    //增加监听，当键退出时收出消息
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
    
    
    containerView.layer.transform = CATransform3DScale(containerView.layer.transform, 0.01, 0.01, 1);
    CABasicAnimation * scale1 = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    scale1.toValue = @(1.3);
    scale1.duration = 0.1;
    scale1.fillMode = kCAFillModeForwards;
    scale1.removedOnCompletion = NO;
    
    CABasicAnimation * scale2 = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    scale2.toValue = @(1);
    scale2.duration = 0.1;
    scale2.fillMode = kCAFillModeForwards;
    scale2.beginTime = 0.1;
    scale2.removedOnCompletion = NO;
    
    CABasicAnimation * scale3 = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    scale3.toValue = @(1.3);
    scale3.duration = 0.1;
    scale3.beginTime = 0.2;
    scale3.fillMode = kCAFillModeForwards;
    scale3.removedOnCompletion = NO;
    
    CABasicAnimation * scale4 = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    scale4.toValue = @(1);
    scale4.duration = 0.1;
    scale4.fillMode = kCAFillModeForwards;
    scale4.beginTime = 0.3;
    scale4.removedOnCompletion = NO;
    
    CAAnimationGroup * group = [CAAnimationGroup animation];
    group.animations = @[scale1,scale2,scale3,scale4];
    group.fillMode = kCAFillModeForwards;
    group.removedOnCompletion = NO;
    group.delegate = self;
    [containerView.layer addAnimation:group forKey:nil];
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    [self dismissAlert];
    alertHandleWithTextFiled handle = objc_getAssociatedObject(self, &kHandleBlock);
    if(handle){
        handle(0,textField);
    }
    return YES;
}


//当键盘出现或改变时调用
- (void)keyboardWillShow:(NSNotification *)aNotification
{
    UIView * contentView = objc_getAssociatedObject(self, &kContainerView);
    
    NSNumber * nnnn = objc_getAssociatedObject(self, &kContainerViewBotton);
    CGFloat  contentViewBotton = [nnnn floatValue];
    contentView.y = contentViewBotton - contentView.height;
    //获取键盘的高度
    NSDictionary *userInfo = [aNotification userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    CGFloat keyboardY = keyboardRect.origin.y;
    
    
    CGFloat offset = keyboardY - contentViewBotton;
    
    
    if(offset<0){
        contentView.y =  contentView.y + offset - 20;
    }else{
        
    }
}

//当键退出时调用
- (void)keyboardWillHide:(NSNotification *)aNotification
{
    UIView * contentView = objc_getAssociatedObject(self, &kContainerView);
    
    NSNumber * nnnn = objc_getAssociatedObject(self, &kContainerViewBotton);
    CGFloat  contentViewBotton = [nnnn floatValue];
    contentView.y = contentViewBotton - contentView.height;
    
}

@end

